import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { useContact } from '@/hooks/useContact'
import { ContactFormData } from '@/lib/api/contact'

export const ContactFormExample: React.FC = () => {
  const { t } = useTranslation()
  const { isSubmitting, submitForm, validateForm } = useContact()

  const [formData, setFormData] = useState<ContactFormData>({
    name: '',
    email: '',
    company: '',
    subject: '',
    message: ''
  })

  const [errors, setErrors] = useState<Partial<Record<keyof ContactFormData, string>>>({})
  const [touched, setTouched] = useState<Partial<Record<keyof ContactFormData, boolean>>>({})

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))

    // 清除错误
    if (errors[name as keyof ContactFormData]) {
      setErrors(prev => ({
        ...prev,
        [name]: undefined
      }))
    }
  }

  // 处理输入失焦
  const handleBlur = (field: keyof ContactFormData) => {
    setTouched(prev => ({
      ...prev,
      [field]: true
    }))

    // 实时验证
    const validation = validateForm(formData)
    if (validation.errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: validation.errors[field]
      }))
    }
  }

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // 标记所有字段为已触碰
    const allTouched = Object.keys(formData).reduce((acc, key) => {
      acc[key as keyof ContactFormData] = true
      return acc
    }, {} as typeof touched)

    setTouched(allTouched)

    // 验证表单
    const validation = validateForm(formData)
    if (!validation.isValid) {
      setErrors(validation.errors)
      toast.error('请检查表单填写是否正确')
      return
    }

    // 提交表单
    const success = await submitForm(formData)
    if (success) {
      // 重置表单
      setFormData({
        name: '',
        email: '',
        company: '',
        subject: '',
        message: ''
      })
      setErrors({})
      setTouched({})
    }
  }

  return (
    <div className="max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-lg">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">联系我们</h2>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 姓名 */}
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
            姓名 <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
            onBlur={() => handleBlur('name')}
            className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
              errors.name && touched.name ? 'border-red-500' : 'border-gray-300'
            }`}
            placeholder="请输入您的姓名"
            disabled={isSubmitting}
          />
          {errors.name && touched.name && (
            <p className="mt-1 text-sm text-red-600">{errors.name}</p>
          )}
        </div>

        {/* 邮箱 */}
        <div>
          <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
            邮箱 <span className="text-red-500">*</span>
          </label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            onBlur={() => handleBlur('email')}
            className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
              errors.email && touched.email ? 'border-red-500' : 'border-gray-300'
            }`}
            placeholder="请输入您的邮箱地址"
            disabled={isSubmitting}
          />
          {errors.email && touched.email && (
            <p className="mt-1 text-sm text-red-600">{errors.email}</p>
          )}
        </div>

        {/* 公司 */}
        <div>
          <label htmlFor="company" className="block text-sm font-medium text-gray-700 mb-2">
            公司
          </label>
          <input
            type="text"
            id="company"
            name="company"
            value={formData.company}
            onChange={handleInputChange}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="请输入您的公司名称（可选）"
            disabled={isSubmitting}
          />
        </div>

        {/* 主题 */}
        <div>
          <label htmlFor="subject" className="block text-sm font-medium text-gray-700 mb-2">
            主题 <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            id="subject"
            name="subject"
            value={formData.subject}
            onChange={handleInputChange}
            onBlur={() => handleBlur('subject')}
            className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
              errors.subject && touched.subject ? 'border-red-500' : 'border-gray-300'
            }`}
            placeholder="请输入消息主题"
            disabled={isSubmitting}
          />
          {errors.subject && touched.subject && (
            <p className="mt-1 text-sm text-red-600">{errors.subject}</p>
          )}
        </div>

        {/* 消息 */}
        <div>
          <label htmlFor="message" className="block text-sm font-medium text-gray-700 mb-2">
            消息内容 <span className="text-red-500">*</span>
          </label>
          <textarea
            id="message"
            name="message"
            rows={5}
            value={formData.message}
            onChange={handleInputChange}
            onBlur={() => handleBlur('message')}
            className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
              errors.message && touched.message ? 'border-red-500' : 'border-gray-300'
            }`}
            placeholder="请输入您的消息内容"
            disabled={isSubmitting}
          />
          {errors.message && touched.message && (
            <p className="mt-1 text-sm text-red-600">{errors.message}</p>
          )}
          <p className="mt-1 text-sm text-gray-500">
            {formData.message.length}/1000 字符
          </p>
        </div>

        {/* 提交按钮 */}
        <button
          type="submit"
          disabled={isSubmitting}
          className={`w-full py-2 px-4 rounded-md text-white font-medium transition-colors ${
            isSubmitting
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2'
          }`}
        >
          {isSubmitting ? '发送中...' : '发送消息'}
        </button>
      </form>
    </div>
  )
}

export default ContactFormExample
